export function checkWeight(root) {
    if (root.children.length === 0) {
        return true
    }
    let sum = 0
    for (let i = 0; i < root.children.length; i++) {
        sum += Number(root.children[i].weight)
    }
    if (sum !== 1) {
        return false
    }
    for (let i = 0; i < root.children.length; i++) {
        if (!checkWeight(root.children[i])) {
            return false
        }
    }
    return true
}

export function buildTree(arr, pid) {
    const res = []

    for (let i = 0; i < arr.length; i++) {
        const data = arr[i]
        if (data.pid === pid) {
            const node = {
                ...data,
                children: buildTree(arr, data.id)
            }

            res.push(node)
        }
    }

    return res
}

export function buildArr(tree) {
    const res = []

    function dfs(tree, res) {
        const length = tree.length

        for (let i = 0; i < length; i++) {
            const node = tree[i]
            if (node.children) {
                dfs(node.children, res)
                delete node.children
            }

            res.push(node)
        }
    }

    dfs(tree, res)

    return res
}

export function findNodeById(id, node) {
    if (node.id === id) {
        return node
    } else if (node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
            const foundNode = findNodeById(id, node.children[i])
            if (foundNode) {
                return foundNode
            }
        }
    }
    return null
}
